package com.xzzz.backend.bsms.server.rbac.sys.captcha;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import com.xzzz.common.base.util.PrimaryKeyUtil;
import com.xzzz.common.base.util.spring.SpringUtil;
import com.xzzz.backend.bsms.server.rbac.sys.captcha.pojo.CaptchaImg;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@AllArgsConstructor
public class CaptchaImgService {

    private final StringRedisTemplate redisTemplate;
    private static final long captchaTimeout = 3 * 60;

    /**
     * 图片验证码KEY
     */
    public String buildKey(String phone) {
        return SpringUtil.getAppName() + ":captcha_img:" + phone;
    }

    /**
     * 获取图片验证码, 有效期 3 分钟
     * @return 图片验证码
     */
    public CaptchaImg get() {
        AbstractCaptcha captcha = CaptchaUtil.createCircleCaptcha(115, 38, 4, 15);
        // ========== 输出 base64 图片
        String code = captcha.getCode();
        String base64 = captcha.getImageBase64();
        CaptchaImg captchaRes = new CaptchaImg();
        captchaRes.setCaptchaImgKey(PrimaryKeyUtil.nextId());
        captchaRes.setCaptchaImgBase64(base64);
        redisTemplate.opsForValue().set(
                buildKey(String.valueOf(captchaRes.getCaptchaImgKey())),
                code,
                captchaTimeout,
                TimeUnit.SECONDS);
        return captchaRes;
    }

}
